package com.typy.www.tpay.ui.view;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.typy.www.tpay.BuildConfig;
import com.typy.www.tpay.R;
import com.typy.www.tpay.bean.bean.PhotoOperation;
import com.typy.www.tpay.ui.acitivity.ImageAddActivity;
import com.typy.www.tpay.ui.acitivity.ImageBrowserActivity;
import com.typy.www.tpay.ui.dialog.SyMessageDialog;
import com.typy.www.tpay.util.FileUtils;
import com.typy.www.tpay.util.ImageUtils;
import com.typy.www.tpay.util.LocalDisplay;
import com.typy.www.tpay.util.Logutil;
import com.typy.www.tpay.util.UiHelper;

import org.apache.commons.codec.binary.StringUtils;


/**
 * 选择图片的组件，提供图片选择、删除、预览和最近拍摄图片
 *
 * @author zhimingyang
 */

public class HousePhotoOperationView implements OnItemClickListener {

    public static int REQUEST_CODE_SELECTED_HOUSE_PHOTO = 101;
    public static int REQUEST_CODE_TAKE_PHOTO = 102;

    private Activity mActivity;
    private GridView gvPhoto;
    private SelectedPhotoAdapter selectedAdapter;
    private HousePhotoOperationListener listener;

    private List<PhotoOperation> photoOperationList = new ArrayList<PhotoOperation>();

    private int photoType;
    private boolean canChangeType;

    private PopupWindow mPopupWindow;
    private boolean IsSale2RentOrRent2Sale;
    private boolean showShenHeTag = false;             //是否显示审核状态

    public boolean isShowShenHeTag() {
        return showShenHeTag;
    }

    public void setShowShenHeTag(boolean showShenHeTag) {
        this.showShenHeTag = showShenHeTag;
    }

    public boolean isIsSale2RentOrRent2Sale() {
        return IsSale2RentOrRent2Sale;
    }

    public void setIsSale2RentOrRent2Sale(boolean isSale2RentOrRent2Sale) {
        IsSale2RentOrRent2Sale = isSale2RentOrRent2Sale;
        selectedAdapter.notifyDataSetChanged();
    }


    public HousePhotoOperationView(Activity act, int type,
                                   boolean canChangeType) {
        mActivity = act;
        this.photoType = type;
        this.canChangeType = canChangeType;
        gvPhoto = new GridView(mActivity);
        gvPhoto.setNumColumns(4);
        gvPhoto.setVerticalSpacing(10);
        gvPhoto.setHorizontalSpacing(10);
        gvPhoto.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
//        gvPhoto.setBackgroundResource(R.drawable.top_border_bg);
        gvPhoto.setPadding(10, 10, 10, 10);
        gvPhoto.setSelector(R.color.transparent);
        gvPhoto.setOnItemClickListener(this);
        selectedAdapter = new SelectedPhotoAdapter();
        gvPhoto.setAdapter(selectedAdapter);

    }

    public View getView() {
        return gvPhoto;
    }

    public int getPhotoType() {
        return photoType;
    }

    public List<PhotoOperation> getPhotoOperationList() {
        return photoOperationList;
    }

    public void setPhotoOperationList(List<PhotoOperation> photoOperationList) {
        this.photoOperationList = photoOperationList;
        selectedAdapter.notifyDataSetChanged();
        updateSelectedHight();
    }

    public void addPhotoOperation(PhotoOperation po) {
        if (photoOperationList != null && !photoOperationList.contains(po)) {
            photoOperationList.add(po);
            selectedAdapter.notifyDataSetChanged();
            updateSelectedHight();
        }
    }

    public void removeAllPhoto() {
        photoOperationList.clear();
        selectedAdapter.notifyDataSetChanged();
        updateSelectedHight();
    }

    public void setAddPhotoList(List<File> files) {
        ArrayList<PhotoOperation> removeList = new ArrayList<PhotoOperation>();
        for (PhotoOperation po : photoOperationList) {
            if (po.getOperation() == PhotoOperation.OPERATION_ADD)
                removeList.add(po);
        }
        if (removeList.size() > 0)
            photoOperationList.removeAll(removeList);
        for (File file : files) {
            photoOperationList.add(new PhotoOperation(photoType,
                    PhotoOperation.OPERATION_ADD, file.toString()));
        }
        selectedAdapter.notifyDataSetChanged();
        updateSelectedHight();
    }



    private void updateSelectedHight() {
        int count = selectedAdapter.getCount();
        final int row = (count + 3) / 4;
        gvPhoto.postDelayed(new Runnable() {

            @Override
            public void run() {
                gvPhoto.setLayoutParams(new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        selectedAdapter.mHeight * row + (row - 1) * 10 + 20));
            }

        }, 100);
    }

    /**
     * 添加图片
     */
    private void addPhoto() {
        ArrayList<File> files = new ArrayList<File>();
        for (PhotoOperation op : photoOperationList) {
            if (op.getOperation() == PhotoOperation.OPERATION_ADD)
                files.add(new File(op.getPhoto()));
        }
        Intent intent = new Intent(mActivity, ImageAddActivity.class);
        intent.putExtra(ImageAddActivity.IMAGE_MAX_COUNT, 0);
        intent.putExtra(ImageAddActivity.EXTRA_CODE, photoType);
        intent.putExtra(ImageAddActivity.IMAGE_FILE_LIST, files);
        mActivity.startActivityForResult(intent,
                REQUEST_CODE_SELECTED_HOUSE_PHOTO);
    }

    /**
     * 拍照
     */
    private void takePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())) {
            File path = ImageUtils.sdCameraPath();
            File hdFile = new File(path, "Sy"
                    + String.valueOf(System.currentTimeMillis()) + ".jpg");
            Uri uri = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                uri = FileProvider.getUriForFile(mActivity, BuildConfig.APPLICATION_ID + ".fileProvider", hdFile);
            } else {
                uri = Uri.fromFile(hdFile);
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            if (listener != null)
                listener.onTakePhoto(photoType, false, hdFile);
        } else {
            UiHelper.showToast(mActivity, "没有插入SD卡,不能发送高清图片,只能发送小图!");
            if (listener != null)
                listener.onTakePhoto(photoType, true, null);
        }
        mActivity.startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
    }

    public void setListener(HousePhotoOperationListener listener) {
        this.listener = listener;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        if (position >= selectedAdapter.getCount() - 1) {

            showPhotoActionDlg();
        } else {
            PhotoOperation po = selectedAdapter.getPhotoOperation(position);
            if (po != null) {
//                if (po.getOperation() == PhotoOperation.OPERATION_ADD) {  // 本地图片文件
//                    ImageBrowserActivity.browseImageFile(mActivity, new File(po.getPhoto()));
//                } else {
////                    ImageBrowserActivity.browseImageUrl(mActivity, po.getPhoto());
//                    if (StringUtils.isEmpty(po.getDemandId()) || position == 0)
//                        ImageBrowserActivity.browseImageUrl(mActivity, po.getPhoto(), showShenHeTag, po.getSa());
//                    else
//                        ImageBrowserActivity.browseImageUrl(mActivity, po.getPhoto(), showShenHeTag, po.getSa(), po.getDemandId(), po.getId());
//                }
            }
        }
    }

    private OnClickListener deleteClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            PhotoOperation po = (PhotoOperation) v.getTag();
            if (po.getOperation() == PhotoOperation.OPERATION_NONE) {
//                if (RoleFunction.getInstance().iSCanDeletePic()) {
//                    if (po.getSa() == 2) {
//                        DeleteDialog(po);
//                    } else {
//                        po.setOperation(PhotoOperation.OPERATION_DELETE);
//                    }
//                } else {
//                    UiHelper.showToast(mActivity, "您没有删除照片权限，如果需开通，请联系公司系统管理员。", R.drawable.error);
//                }
            } else if (po.getOperation() == PhotoOperation.OPERATION_ADD) {
                photoOperationList.remove(po);
            } else if (po.getOperation() == PhotoOperation.OPERATION_CHANGE_TYPE) {
                po.setType(po.getChangeFromType());
                po.setOperation(PhotoOperation.OPERATION_DELETE);
            }
            selectedAdapter.notifyDataSetChanged();
            updateSelectedHight();
        }


    };

    private void DeleteDialog(final PhotoOperation po) {
        SyMessageDialog dlg = new SyMessageDialog(mActivity,
                SyMessageDialog.TYPE_INFORMATION).setTitleText(
                "该图片已通过审核，若该图片有发放盟币，删除会扣除盟币").setPositiveButton(
                "确定", new SyMessageDialog.OnClickListener() {

                    @Override
                    public void onClick(SyMessageDialog dialog) {
                        po.setOperation(PhotoOperation.OPERATION_DELETE);
                        selectedAdapter.notifyDataSetChanged();
                        updateSelectedHight();
                    }
                });
        dlg.setNegativeButton("取消", new SyMessageDialog.OnClickListener() {

            @Override
            public void onClick(SyMessageDialog dialog) {
                // TODO Auto-generated method stub
                return;
            }
        });
        dlg.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog) {
                return;
            }

        });
        dlg.show();
    }

    private OnClickListener changeTypeClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            PhotoOperation po = (PhotoOperation) v.getTag();
            showChangeTypeDlg(po);
        }

    };

    private void showPhotoActionDlg() {
        View contentView = LayoutInflater.from(mActivity).inflate(
                R.layout.photo_action_selector, null);
        View btnTakePhoto = contentView.findViewById(R.id.btn_take_photo);
        View btnSelect = contentView.findViewById(R.id.btn_select_from_album);
        View btnCancel = contentView.findViewById(R.id.btn_cancel);

        btnTakePhoto.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
                takePhoto();

            }

        });

        btnSelect.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
                addPhoto();
            }

        });

        btnCancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
            }
        });

        mPopupWindow = new PopupWindow(contentView, LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT, true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable(mActivity
                .getResources(), (Bitmap) null));
        mPopupWindow.showAtLocation(gvPhoto, Gravity.NO_GRAVITY, 0, 0);
    }

    private void showChangeTypeDlg(final PhotoOperation po) {
//        OnClickListener click = new OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                SyDictVm hpt = (SyDictVm) v.getTag();
//                if (hpt.getKey() != photoType) {
//                    photoOperationList.remove(po);
//                    selectedAdapter.notifyDataSetChanged();
//                    updateSelectedHight();
//                    if (po.getOperation() == PhotoOperation.OPERATION_NONE) {
//                        po.setOperation(PhotoOperation.OPERATION_CHANGE_TYPE);
//                        po.setChangeFromType(photoType);
//                    }
//                    po.setType(hpt.getKey());
//                    if (listener != null)
//                        listener.onPhotoChangeType(po);
//                }
//                mPopupWindow.dismiss();
//            }
//
//        };
//
//        View contentView = LayoutInflater.from(mActivity).inflate(
//                R.layout.base_dialog, null);
//        TextView tvTitle = (TextView) contentView
//                .findViewById(R.id.tv_dialog_title);
//        LinearLayout llBody = (LinearLayout) contentView
//                .findViewById(R.id.ll_dialog_body_holder);
//        View vBlank = contentView.findViewById(R.id.v_blank);
//        vBlank.setOnClickListener(new OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                mPopupWindow.dismiss();
//            }
//
//        });
//
//        tvTitle.setText("图片分类");
//        int px = LocalDisplay.dp2px(12);
//        for (int i = 0; i < SyConstDict.HousePhotoType.size(); i++) {
//            SyDictVm hpt = SyConstDict.HousePhotoType.get(i);
//            TextView tv = new TextView(mActivity);
//            tv.setTag(hpt);
//            tv.setOnClickListener(click);
//            tv.setText(hpt.getValue());
//            if (i == (SyConstDict.HousePhotoType.size() - 1))
//                tv.setBackgroundResource(R.drawable.clickable_row_bg_selector);
//            else
//                tv.setBackgroundResource(R.drawable.bottom_border_bg_selector);
//            tv.setPadding(px, px, px, px);
//            tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
//            if (hpt.getKey() == photoType)
//                tv.setTextColor(mActivity.getResources().getColor(
//                        R.color.app_red));
//            else
//                tv.setTextColor(mActivity.getResources().getColor(
//                        R.color.content_text_color));
//            llBody.addView(tv, LinearLayout.LayoutParams.MATCH_PARENT,
//                    LinearLayout.LayoutParams.WRAP_CONTENT);
//        }
//
//        mPopupWindow = new PopupWindow(contentView, LayoutParams.MATCH_PARENT,
//                LayoutParams.MATCH_PARENT, true);
//        mPopupWindow.setTouchable(true);
//        mPopupWindow.setOutsideTouchable(true);
//        mPopupWindow.setBackgroundDrawable(new BitmapDrawable(mActivity
//                .getResources(), (Bitmap) null));
//        mPopupWindow.showAtLocation(gvPhoto, Gravity.NO_GRAVITY, 0, 0);
    }

    /**
     * 已选择图片的Adapter
     *
     * @author zhimingyang
     */
    private class SelectedPhotoAdapter extends BaseAdapter {
        private int mHeight;
        private int count = 0;

        private void calcCount() {
            count = 1;
            for (PhotoOperation po : photoOperationList)
                if (po.getOperation() != PhotoOperation.OPERATION_DELETE)
                    count++;
        }

        private PhotoOperation getPhotoOperation(int position) {
            if (position < count - 1) {
                int index = 0;
                for (PhotoOperation po : photoOperationList)
                    if (po.getOperation() != PhotoOperation.OPERATION_DELETE) {
                        if (index == position)
                            return po;
                        index++;
                    }
            }
            return null;
        }

        @Override
        public void notifyDataSetChanged() {
            calcCount();
            super.notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            if (count < 1)
                calcCount();
            return count;
        }

        @Override
        public Object getItem(int position) {
            return getPhotoOperation(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            PhotoHolder holder = null;
            if (convertView == null) {
                convertView = mActivity.getLayoutInflater().inflate(R.layout.house_photo_item, null);
                holder = new PhotoHolder();
                holder.ivPhoto = (ImageView) convertView.findViewById(R.id.iv_photo);
                holder.ivPhoto.setScaleType(ScaleType.CENTER_CROP);
                holder.btnDelete = (ImageButton) convertView.findViewById(R.id.iv_delete);
                holder.btnChangeType = (ImageButton) convertView.findViewById(R.id.iv_change_type);
                holder.llTag = (LinearLayout) convertView.findViewById(R.id.ll_tig);
                holder.ivTag = (ImageView) convertView.findViewById(R.id.iv_tag);
                holder.tvTag = (TextView) convertView.findViewById(R.id.tv_tag);
                convertView.setTag(holder);
            } else {
                holder = (PhotoHolder) convertView.getTag();
            }

//			int width = parent.getWidth();
            int width = LocalDisplay.SCREEN_WIDTH_PIXELS;
            if (width > 0) {
                width = (width - 50) / 4;
                mHeight = width;
                holder.ivPhoto.setLayoutParams(new RelativeLayout.LayoutParams(
                        width, width));
            }
            if (position < count - 1) {
                PhotoOperation po = getPhotoOperation(position);
                if (width > 0) {
                    if (po.getOperation() == PhotoOperation.OPERATION_ADD)
                        UiHelper.setImage(new File(po.getPhoto()), holder.ivPhoto, null);
                    else
                        UiHelper.setImage(po.getPhoto(), holder.ivPhoto, null);
                }
//                if (Ph != null && Ph.getR() == 0) {
//                    holder.btnDelete.setVisibility(View.GONE);
//                } else {
                if (IsSale2RentOrRent2Sale && po.getOperation() == PhotoOperation.OPERATION_NONE) {
                    holder.btnDelete.setVisibility(View.GONE);
                } else {
                    holder.btnDelete.setVisibility(View.VISIBLE);
//                    }
                }
                holder.btnDelete.setTag(po);
                holder.btnDelete.setOnClickListener(deleteClick);
                if (canChangeType) {
                    holder.btnChangeType.setVisibility(View.GONE);
                    holder.btnChangeType.setTag(po);
                    holder.btnChangeType.setOnClickListener(changeTypeClick);
                } else {
                    holder.btnChangeType.setVisibility(View.GONE);
                }
                if (showShenHeTag && po.getOperation() != PhotoOperation.OPERATION_ADD) {
//                    if (po.getSa() == 0) {      //未提交审核
//                        holder.llTag.setVisibility(View.GONE);
//                        holder.llTag.setBackgroundColor(parent.getResources().getColor(R.color.red_e34444));
//                        holder.ivTag.setImageDrawable(parent.getResources().getDrawable(R.drawable.shenhe_false));
//                        holder.tvTag.setText("未提交审核");
//
//                    } else if (po.getSa() == 1) { //等待审核
//                        holder.llTag.setVisibility(View.GONE);
//                        holder.llTag.setBackgroundColor(parent.getResources().getColor(R.color.red_e34444));
//                        holder.ivTag.setImageDrawable(parent.getResources().getDrawable(R.drawable.shenhe_false));
//                        holder.tvTag.setText("等待审核");
//
//                    } else if (po.getSa() == 2) {  //审核通过
//                        holder.llTag.setVisibility(View.VISIBLE);
//                        holder.llTag.setBackgroundColor(parent.getResources().getColor(R.color.green1cc300));
//                        holder.ivTag.setImageDrawable(parent.getResources().getDrawable(R.drawable.shenhe_true));
//                        holder.tvTag.setText("通过");
//
//                    } else if (po.getSa() == 3) {   //审核不通过
//                        holder.llTag.setVisibility(View.VISIBLE);
//                        holder.llTag.setBackgroundColor(parent.getResources().getColor(R.color.red_e34444));
//                        holder.ivTag.setImageDrawable(parent.getResources().getDrawable(R.drawable.shenhe_false));
//                        holder.tvTag.setText("不通过");
//                    } else {
                    holder.llTag.setVisibility(View.GONE);
//                    }
                } else {
                    holder.llTag.setVisibility(View.GONE);
                }
            } else {
                if (width > 0) {
                    UiHelper.setImage(R.drawable.tousujianyi_zhaopian, holder.ivPhoto, null);
                }
                holder.btnDelete.setVisibility(View.GONE);
                holder.btnDelete.setTag(null);
                holder.btnDelete.setOnClickListener(null);
                holder.btnChangeType.setVisibility(View.GONE);
                holder.btnChangeType.setTag(null);
                holder.btnChangeType.setOnClickListener(null);
                holder.llTag.setVisibility(View.GONE);
            }
            return convertView;
        }

        private class PhotoHolder {
            private ImageView ivPhoto;
            private ImageButton btnDelete;
            private ImageButton btnChangeType;
            private LinearLayout llTag;
            private ImageView ivTag;
            private TextView tvTag;
        }

    }

    public interface HousePhotoOperationListener {
        public void onPhotoChangeType(PhotoOperation po);

        public void onTakePhoto(int photoType, boolean isThumb, File hdFile);
    }
}
